package net.whg.datasource;

import net.whg.datasource.DataSourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
@Primary
public class DynamicDataSource extends AbstractRoutingDataSource {

    //当前使用的数据源标识
    public static ThreadLocal<String> name = new ThreadLocal<>();

    @Autowired
    private DataSource dataSource1;

    @Autowired
    private DataSource dataSource2;

    @Override
    public void afterPropertiesSet() {
        //为targetDataSources设置数据源
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER, dataSource1);
        targetDataSources.put(DataSourceType.SLAVE, dataSource2);
        super.setTargetDataSources(targetDataSources);
        //为defaultTargetDataSource设置数据源
        super.setDefaultTargetDataSource(dataSource1);
        super.afterPropertiesSet();
    }

    /**
     * 返回当前数据源标识
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return name.get();
    }
}
